<template>
	<z-paging ref="paging" use-chat-record-mode safe-area-inset-bottom v-model="dataList">
		<view slot="top">
			<u-notice-bar
				text="1、免费测试版本仅供体验使用；2、大模型也可能会犯错，请核查重要信息；3、如需正式账号请发送邮件申请，邮箱地址：haoyuejie@sinsegye.com.cn"></u-notice-bar>
		</view>
		<!-- content -->
		<view v-for="(item,index) in dataList" :key="index">
			<chat-item :item="item"></chat-item>
		</view>
		<view slot="bottom" class="safe-area-inset-bottom">
			<view class="flex align-center p-2">
				<view v-if="!showSend" class="font flex flex-1 radius-16 border color-content shadow-3 p-2" @click="showHandle">
					你可以向我提问
				</view>
				</u-text>
				<view v-else class="shadow-3 flex flex-column flex-1 r adius-16 p-1">
					<u--textarea class="radius-12" :maxlength="10000" border="none" placeholder="你可以向我提问" v-model="message"></u--textarea>
					<view class="flex justify-end pr-1 pb-1">
						<view>
							<u-button type="primary" size="small" :disabled="isDisabled" shape="circle" text="发送" @click="doSend"></u-button>
						</view>
					</view>
				</view>
			</view>
			<u-toast ref="uToast" />
		</view>
		<u-modal :show="showAuth" :showConfirmButton="false">
			<view class="slot-content">
				<view class="flex flex-column justify-center align-center mb-4">
					<view class="font-md font-weight-bold color-main">绑定手机号</view>
					<view class="font mt-2 color-tips">请先绑定手机号再进行操作</view>
				</view>
				<!-- <u-button type="primary" open-type="getPhoneNumber" shape="circle" @getphonenumber="decryptPhoneNumber"
					@click="showAuth = false">获取手机号</u-button> -->
					<u-button type="primary" open-type="getPhoneNumber" shape="circle" @getphonenumber="decryptPhoneNumber"
						>获取手机号</u-button>
			</view>
		</u-modal>
	</z-paging>
</template>

<script>
	import { local } from '@/common/local'
	import { checkUserInfo, getUserId, userLogin, chatModel, userLogout } from '@/api/index.js'
	import { get } from 'https'
	import { stringify } from 'querystring'
	import { debounce } from 'lodash'
	let count = 0
	export default {
		data() {
			return {
				openId: '',
				isExist: false,
				showAuth: false,
				hasLogin: false,
				showSend: false,
				title: 'content',
				dataList: [],
				toke: null,
				message: null,
				wsList: '',
				aiId: 1,
				info: '',
				wsOpen: false,
				wsMessage: null,
				isDisabled: false,
				isEndTag: true
			}
		},
		onLoad() {
			// checkUserInfo({open_id: 'ocI8h7WTOdZqdqEF2OjiheKvLJm3'}).then(res => {
			// 	this.isExist = res.isExist
			// })
			// 
			local.set('user', {
				openId: 'ocI8h7WTOdZqdqEF2OjiheKvLJm5'
			})
			this.checkUser()
		},
		onUnload() {
			const token = local.get('token')
			userLogout({ state: 'out', token }).then(res => {
				if(res.code ===200) {
					local.remove('token')
				}
			})
		},
		methods: {
			decryptPhoneNumber(e) {
				if (e.detail.code) {
					getUserId({
						code: e.detail.code
					}).then(res => {
						this.showAuth = false
						local.set('user', {
							openId: res.openId
						})
					})
				}
			},
			checkUser() {
				const userInfo = local.get('user')
				const token = local.get('token')
				if (userInfo.openId) {
					this.openId = userInfo.openId
					checkUserInfo({
						open_id: userInfo.openId
					}).then(res => {
						this.isExist = res.isExist
						if (token === '' || token === undefined) {
							this.getToken()
						}
					})
				}
			},
			showHandle() {
				if (this.openId) {
					if (this.isExist) { // 用户信息已完善
						this.showSend = true
					} else {
						uni.showModal({
							title: '请完善个人信息',
							content: '',
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/index/form'
									})
								}
							}
						});
					}
				} else {
					this.showAuth = true
				}
			},
			// 监听键盘高度改变，请不要直接通过uni.onKeyboardHeightChange监听，否则可能导致z-paging内置的键盘高度改变监听失效（如果不需要切换表情面板则不用写）
			keyboardHeightChange(res) {
				this.$refs.inputBar.updateKeyboardHeightChange(res);
			},
			// 用户尝试隐藏键盘，此时如果表情面板在展示中，应当通知chatInputBar隐藏表情面板（如果不需要切换表情面板则不用写）
			hidedKeyboard() {
				this.$refs.inputBar.hidedKeyboard();
			},
			// 发送前登录
			getToken() {
				userLogin({state: 'in'}).then(res => {
					if(res.code !== 200) {
						this.$refs.uToast.show({
							message: res.message,
							type: 'warning'
						})
						this.isDisabled = true
						return
					}
					local.set('token', res.token)
				})
			},
			updateChatMessage(messageId, newContent) {
				const index = this.dataList.findIndex(item => item.id === messageId);
				if (index !== -1) {
				  this.dataList[index].content = newContent;
				}
			},
			getWS() {
				uni.connectSocket({
					url: 'ws://www.lhtllm.com',
					// url: 'ws://172.16.1.63:19997',
					success: (res) => {
						console.log('连接成功')
						uni.sendSocketMessage({
							data: JSON.stringify({
								message: this.wsMessage,
								token: local.get('token')
							}),
						})
					},
					fail: (res) => {
						console.log('连接失败')
					}
				}),
				uni.onSocketOpen((res) => {
				  console.log('WebSocket连接已打开')
					uni.sendSocketMessage({
						data: JSON.stringify({
							message: this.wsMessage,
							token: local.get('token')
						}),
						success: () => {
							console.log('信息发送成功')
						}
					})
					this.wsOpen = true
				});
				      
				// 监听WebSocket消息事件
				uni.onSocketMessage((res) => {
					const data = JSON.parse(res.data)
					const tag = "```"
					if (data.content == tag) { // 当前为markdown标记
						count++
						if (count % 2 == 1) { // 未找到结束标记
							this.isEndTag = false
						} else {
							this.isEndTag = true
						}
					}
					let _newMsg = this.wsList
					if (!this.isEndTag) {
						if (data.content != tag) {
							if(!_newMsg.endsWith("```")) {
								_newMsg = _newMsg + data.content + " ```"
							} else {
								_newMsg = this.replaceLastOccurrence(_newMsg, "\n```") + data.content + "\n```"
							}
						} else {
							_newMsg = _newMsg + data.content + " \n```"
						}
					} else {
						_newMsg += data.content
					}
					this.wsList = _newMsg
					
					this.updateChatMessage(this.aiId, this.wsList)
					this.info = ''
					if(data.event === 'ldone') {
						this.wsList = ''
						this.isDisabled = false
					}
				});
			},
			// 发送新消息
			doSend(msg) {
				if (token === '' || token === undefined) {
					// this.getToken()
				}
				const token = local.get('token')
				this.wsOpen = false
				this.wsMessage = this.message
				// this.getTask1()
				this.dataList.forEach(item => {
					if(item.id && item.id === this.aiId) {
						delete item.id
					}
				})
				this.$refs.paging.addChatRecordData({
					time: '',
					icon: '/static/user.png',
					name: 'Admin',
					content: this.message,
					isMe: true
				});
				this.message = ''
				uni.showLoading({
					title: '查询中...'
				})
				chatModel({ token, message: this.message }).then(res => {
					if(res.code === 200) {
						this.getWS()
						this.isDisabled = true
						setTimeout(() => {
							this.$refs.paging.addChatRecordData({
								time: '',
								icon: '/static/ai.png',
								name: 'AI',
								content: '请稍后',
								isMe: false,
								id: this.aiId
							});
						}, 500)
						uni.hideLoading()
					}
				}).catch(res => {
					setTimeout(() => {
						uni.hideLoading()
					}, 4000)
				})
			},
			replaceLastOccurrence(str, search) {  
			    const lastIndex = str.lastIndexOf(search);  
			    if (lastIndex === -1) {  
			        // 如果没有找到，则直接返回原始字符串  
			        return str;  
			    }  
			    // 切割字符串为两部分：匹配项之前和匹配项之后（但在这个情况下，我们只关心之前）  
			    // 然后将替换字符串与剩余部分连接起来  
			    return str.slice(0, lastIndex);  
			}
		}
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	
	/deep/ .u-modal__content {
		transform: scaleY(-1);
	}
</style>